/*************************************************************************
	> File Name: leetcode23.合并K个升序链表_v2.c
	> Author: Maureen 
	> Mail: Maureen@qq.com 
	> Created Time: 五  9/24 17:23:27 2021
 ************************************************************************/

//分治合并
//时间复杂度：O(kn x logk)
//空间复杂度：O(logk)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        return merge(lists, 0, lists.size() - 1);
    }

    ListNode *merge(vector<ListNode *>& lists, int left, int right) {
        if (left == right) return lists[left];
        if (left > right) return nullptr;
        int mid = (left + right) >> 1;
        return merge2Lists(merge(lists, left, mid), merge(lists, mid + 1, right));
    }

    ListNode *merge2Lists(ListNode *l1, ListNode *l2) {
        ListNode *head = new ListNode(0);
        ListNode *pre = head;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                pre->next = l1;
                l1 = l1->next;
            } else {
                pre->next = l2;
                l2 = l2->next;
            }
            pre = pre->next;
        }
        pre->next = l1 == nullptr ? l2 : l1;
        return head->next;
    }
};
